<!--
 * @Author: weikang
 * @Description:
 * @Date: 2023-12-23 11:41:29
 * @LastEditTime: 2024-05-21 22:15:10
 * @FilePath: \env-manager-pc\src\views\data_query\power_off\index.vue
-->
<script setup lang="ts">
import dayjs from 'dayjs'
import { usePage } from '@/utils/commonHook'
import { useEnvOrgs, useOwnerOrgs } from '@/utils/dataHook'
import { FilterQuery2 } from '@/utils/dataHook/data'
import dataQueryApi from '@/api/modules/data.query'
import useKeepAliveStore from '@/store/modules/keepAlive'
import useUserStore from '@/store/modules/user'

defineOptions({
  name: 'DataPowerOffList',
})
const keepAliveStore = useKeepAliveStore()

onBeforeRouteLeave((to) => {
  if (to.name === 'data-power-off-detail') {
    keepAliveStore.add('DataPowerOffList')
  }
  else {
    keepAliveStore.remove('DataPowerOffList')
  }
})

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const tableData = ref<any[]>([])
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

const searchData = reactive(new FilterQuery2({
  Filters: [{
    ObjTypeKey: 'Enterprise',
    Type: 'DIM.Business.Envs.EnterpriseFilters.EnvOrgGUIDFilter',
  }, {
    ObjTypeKey: 'Enterprise',
    Type: 'DIM.Units.Filters.NameFilter',
  }, {
    ObjTypeKey: 'Enterprise',
    Type: 'DIM.Units.Filters.OwnerOrgGUIDFilter',
  }, {
    ObjTypeKey: 'Device',
    Type: 'DIM.Devices.Filters.AssetCodeFilter',
  }],
}))

interface TimeRangeType {
  startTime: string | null
  endTime: string | null
}

const timeRange = reactive<TimeRangeType>({
  startTime: dayjs().subtract(1, 'day').format('YYYYMMDD'),
  endTime: dayjs().add(1, 'day').format('YYYYMMDD'),
})

const { startTime, endTime } = route.query || {}
if (startTime) {
  timeRange.startTime = startTime as string
}
if (endTime) {
  timeRange.endTime = endTime as string
}

const tiemValue = computed({
  set: (values) => {
    const realValues = values || []
    timeRange.startTime = realValues[0]
    timeRange.endTime = realValues[1]
  },
  get: () => {
    return [timeRange.startTime, timeRange.endTime]
  },
})

const defaultProps = {
  children: 'Children',
  label: 'Name',
}

const OwnerList = userStore.isEnterpris ? [] : useOwnerOrgs()
const envOrgs = userStore.isEnterpris ? [] : useEnvOrgs()

const loading = ref(false)
async function getTableData() {
  loading.value = true
  const res = await dataQueryApi.GetDevicePowerSupplyStatDetail({
    startTime: timeRange.startTime,
    endTime: dayjs(timeRange.endTime).add(1, 'day').format('YYYYMMDD'),
    filters: searchData.getQuery(),
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  const { Rows, RecordsetCount } = res
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

function search() {
  page.PageNum = 1
  getTableData()
}

getTableData()

function toDetail(row: any) {
  sessionStorage.setItem('ent_power_off', JSON.stringify(row))
  router.push(`/data-query/power-off/detail/${row.DeviceObjID}?startTime=${timeRange.startTime}&endTime=${timeRange.endTime}`)
}
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol v-if="!userStore.isEnterpris" :span="6">
              <ElFormItem label="管理机构">
                <el-tree-select
                  v-model="searchData['DIM.Business.Envs.EnterpriseFilters.EnvOrgGUIDFilter']"
                  value-key="Code"
                  :data="envOrgs"
                  class="w-full"
                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable check-strictly
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="企业名称">
                <ElInput v-model="searchData['DIM.Units.Filters.NameFilter']" clearable placeholder="请输入" />
              </ElFormItem>
            </ElCol>
            <ElCol v-if="!userStore.isEnterpris" :span="6">
              <ElFormItem label="运维公司">
                <el-tree-select
                  v-model="searchData['DIM.Units.Filters.OwnerOrgGUIDFilter']"
                  value-key="Code"
                  :data="OwnerList"
                  check-strictly
                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="userStore.isEnterpris ? 12 : 0">
              <ElFormItem label="日期">
                <ElDatePicker v-model="tiemValue" value-format="YYYYMMDD" type="daterange" :clearable="false" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="18" class="flex flex-justify-end">
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
              <ElButton type="success">
                新增
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table
          height="100%"
          auto-resize border
          :data="tableData"
          :loading="loading"
          :row-config="{ isCurrent: true }"
        >
          <VxeColumn type="seq" title="序号" width="80" />
          <VxeColumn field="EnvOrgName" title="管理机构" min-width="100" />
          <VxeColumn field="OwnerOrgName" title="运维公司" min-width="100" />
          <VxeColumn field="EntName" title="企业名称" min-width="100" />
          <VxeColumn field="DeviceName" title="设备名称" min-width="100" />
          <VxeColumn field="DeviceAsset" title="设备编码" min-width="100" />
          <VxeColumn field="Count" title="停上电事件数" width="150">
            <template #default="{ row }">
              <el-button link type="primary" @click="toDetail(row)">
                {{ row.Count }}
              </el-button>
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4"
        :page-size="page.PageSize"
        :total="page.RecordsetCount"
        :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
    </PageMain>
  </div>
</template>
